package com.kzz.dialoglibraries.dialog;

import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.RelativeLayout;

import androidx.annotation.NonNull;

import com.kzz.dialoglibraries.DialogSetDateInterface;
import com.kzz.dialoglibraries.R;
import com.kzz.dialoglibraries.TimeInterface;
import com.kzz.dialoglibraries.utils.ActivityUtils;

import java.text.MessageFormat;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 自定义dialog
 * <p>
 * Created by zhangzhao.ke on 2018/6/7.
 */

public class DialogCreate extends Dialog {

    protected Activity mActivity;//上下文
    private int addViewId;//插入的view的id
    private View inflaterView;//插入的view
    private DialogSetDateInterface dialogSetDateInterface;//设置：插入布局中的控件、数据更改显示的接口
    private boolean isBackKeyCancelable;////点击物理返回键是否可以关闭弹窗。
    private boolean isCloseDialogOutSide;//点击弹窗内面是否关闭弹窗
    private int backgroundRes;
    private boolean isTransparent;//是否半透明:true表示是透明，fales表示半透明背景。
    private RelativeLayout rlAllDialogLayout;
    private Timer timer;
    private TimerTask timerTask;
    private Handler handler;
    private static int MAX_TIME = -1;//无操作自动关闭
    private TimeInterface timeInterface;//倒计时回调
    private boolean isNavigationBarHide = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        initDate();
        initEvent();
    }

    /**
     * 构造方法
     *
     * @param mActivity        上下文环境
     * @param addViewId        自定义的布局，将此布局插入到dialog中显示
     * @param setDateInterface 设置：插入布局中的控件、数据更改显示
     */
    public DialogCreate(@NonNull Activity mActivity, int addViewId, DialogSetDateInterface setDateInterface) {
        super(mActivity, R.style.AlertDialog);
        this.mActivity = mActivity;
        this.addViewId = addViewId;
        this.dialogSetDateInterface = setDateInterface;
    }

    public DialogCreate(@NonNull Activity mActivity, int addViewId, int themeResId, DialogSetDateInterface setDateInterface) {
        super(mActivity, themeResId);
        this.mActivity = mActivity;
        this.addViewId = addViewId;
        this.dialogSetDateInterface = setDateInterface;
    }

    /**
     * 构造方法
     *
     * @param mActivity 上下文环境
     * @param builder   创建者对象
     */
    private DialogCreate(@NonNull Activity mActivity, Builder builder) {
        super(mActivity, builder.style);
        this.mActivity = mActivity;
        this.isTransparent = builder.isTransparent;
        this.addViewId = builder.addViewId;
        this.dialogSetDateInterface = builder.dialogSetDateInterface;
        this.isBackKeyCancelable = builder.isBackKeyCancelable;
        this.isCloseDialogOutSide = builder.isCloseDialogOutSide;
        this.backgroundRes = builder.backgroundRes;
        this.MAX_TIME = builder.MAX_TIME;
        this.timeInterface = builder.timeInterface;
        this.isNavigationBarHide = builder.isNavigationBarHide;
    }

    /**
     * 初始化控件，自定义布局插入到dialog中
     */
    private void initView() {
        if (getWindow() != null) {
            View view = getWindow().getLayoutInflater().inflate(R.layout.dialog_base, null);
            rlAllDialogLayout = view.findViewById(R.id.ll_add_textview);
            View inflaterView = LayoutInflater.from(mActivity).inflate(addViewId, rlAllDialogLayout, false);
            this.inflaterView = inflaterView;
            rlAllDialogLayout.setBackgroundResource(backgroundRes);
            rlAllDialogLayout.addView(inflaterView);
            if (isCloseDialogOutSide) {
                rlAllDialogLayout.setOnClickListener(v -> {
                    dismiss();
                });
            }
            inflaterView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                }
            });
            setContentView(view);
            getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            if (isNavigationBarHide) {
                WindowManager.LayoutParams params = getWindow().getAttributes();
                params.systemUiVisibility = (
                        View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
                                View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY |
                                View.SYSTEM_UI_FLAG_FULLSCREEN
                );
                getWindow().setAttributes(params);
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            }
        }
    }

    /**
     * 设置new dialogSetDateInterface接口中的数据
     * inflaterView 插入的布局view 对象。
     */
    private void initDate() {
        dialogSetDateInterface.setDate(inflaterView, this);
    }

    /**
     * 初始化关闭按钮监听
     */
    private void initEvent() {
        setCancelable(isBackKeyCancelable);
    }


    @Override
    public void show() {
        if (!ActivityUtils.isDestroy(mActivity)) {
            super.show();
            if (MAX_TIME > 0)
                startTime();
        }
    }

    @Override
    public void dismiss() {
        try {
            if (handler != null)
                handler.removeCallbacksAndMessages(null);
            stopTime();
            if (!ActivityUtils.isDestroy(mActivity))
                super.dismiss();
        } catch (Exception e) {

        }
    }

    /**
     * 充满屏幕显示dialog
     * show:显示dialog（自定义透明度的得用这个方法，不能用show,不然屏幕不能充满）
     */
    public void myShow() {
        show();
        if (getWindow() != null) {
            WindowManager.LayoutParams lp = getWindow().getAttributes();
            lp.width = WindowManager.LayoutParams.MATCH_PARENT; //设置宽度
            lp.height = WindowManager.LayoutParams.MATCH_PARENT; //设置高度
            getWindow().setAttributes(lp);
        }
    }

    /**
     * 使用单例模式弹出
     */
    public void showSingle() {
        DialogCreateSingleUtils.getInstance().showDialogMsg(this);
    }

    public void showNoDouble() {
        NoDoubleUtils.show(this);
    }

    private void initTime() {
        timer = new Timer();
        timerTask = new TimerTask() {
            @Override
            public void run() {
                if (inflaterView.getVisibility() == View.VISIBLE) {
                    Message message = new Message();
                    Bundle bundle = new Bundle();
                    bundle.putInt("time", MAX_TIME);
                    message.setData(bundle);
                    if (MAX_TIME <= 0) {
                        //停止时间，关闭派梯view，通知人脸下个继续
                        message.what = 0;
                    } else {
                        message.what = 1;
                    }
                    handler.sendMessage(message);
                    MAX_TIME--;
                }
            }
        };
        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(@NonNull Message msg) {
                switch (msg.what) {
                    case 0:
                        dismiss();
                        if (timeInterface != null)
                            timeInterface.onEnd(DialogCreate.this);
                        break;
                    case 1:
//                        tvTime.setText(MessageFormat.format("{0}s", MAX_TIME));
//                        tvTime.setVisibility(View.VISIBLE);
                        if (timeInterface != null)
                            timeInterface.onTime(inflaterView, MAX_TIME);
                        Log.d("弹窗倒计时", "时间=" + MessageFormat.format("{0}s", MAX_TIME));
                        break;
                }
                return false;
            }
        });
    }

    /**
     * 有操作，更新倒计时
     */
    private void updateMaxTime() {
        MAX_TIME = 5;
    }

    private void updateMaxTime(int time) {
        MAX_TIME = time;
    }

    private void startTime() {
        stopTime();
        initTime();
        timer.schedule(timerTask, 0, 1000);
    }

    private void stopTime() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (timerTask != null) {
            timerTask.cancel();
            timerTask = null;
        }
    }


    /**
     * builder创建者
     */
    public static class Builder {
        private int addViewId;//插入的view的id
        private DialogSetDateInterface dialogSetDateInterface;//设置：插入布局中的控件、数据更改显示的接口
        private boolean isTransparent;//是否透明
        private Activity mActivity;//上下文
        private int style = R.style.AlertDialog;//半透明，透明指数：0.35;
        private boolean isCloseDialogOutSide = true;//点击弹窗外部是否关闭弹窗
        private int backgroundRes;
        private boolean isBackKeyCancelable = true;//点击物理返回键是否可以关闭弹窗。
        private int MAX_TIME = -1;//无操作自动关闭
        private TimeInterface timeInterface;//倒计时回调
        private boolean isNavigationBarHide = false;//是否隐藏底部导航栏


        public Builder(Activity mActivity) {
            this.mActivity = mActivity;
        }

        /**
         * 设置：是否透明 ，默认是半透明
         *
         * @param isTransparent 是否透明
         * @return 返回布尔值
         */
        public Builder setIsTransparent(boolean isTransparent) {
            this.isTransparent = isTransparent;
            if (isTransparent) {//是否透明
                this.style = R.style.AlertDialog2;//全透明，透明指数：0
            } else {
                this.style = R.style.AlertDialog;//半透明，透明指数：0.35
            }
            return this;
        }

        /**
         * 设置弹窗风格style
         *
         * @param style 弹窗风格style
         * @return Builder
         */
        public Builder setStyle(int style) {
            this.style = style;
            return this;
        }

        /**
         * 设置：插入的弹窗viewId
         *
         * @param addViewId 插入的弹窗viewId
         * @return Builder
         */
        public Builder setAddViewId(int addViewId) {
            this.addViewId = addViewId;
            return this;
        }

        /**
         * 插入的弹窗view，进行设置控件的数据回调接口，
         *
         * @param dialogSetDateInterface 回调
         * @return 返回Builder
         */
        public Builder setDialogSetDateInterface(DialogSetDateInterface dialogSetDateInterface) {
            this.dialogSetDateInterface = dialogSetDateInterface;
            return this;
        }

        /**
         * 设置弹窗外部点击是否能够关闭弹窗
         *
         * @param isClose boolean
         * @return 返回Builder
         */
        public Builder setIsCloseDialogOutSide(boolean isClose) {
            this.isCloseDialogOutSide = isClose;
            return this;
        }

        public Builder setBackgroundRes(int res) {
            this.backgroundRes = res;
            return this;
        }

        /**
         * 设置点击物理返回键是否可以关闭弹窗
         *
         * @param isClose boolean
         * @return 返回Builder
         */
        public Builder setIsBackKeyCancelable(boolean isClose) {
            this.isBackKeyCancelable = isClose;
            return this;
        }

        /**
         * 是否隐藏底部导航栏
         * @param isHide ture隐藏、false 显示
         * @return
         */
        public Builder isNavigationBarHide(boolean isHide) {
            this.isNavigationBarHide = isHide;
            return this;
        }

        /**
         * 是否隐藏上面状态栏
         * @param isHide ture隐藏、false 显示
         * @return
         */
        public Builder isStatusBarHide(boolean isHide) {
            if (isHide) {
                setStyle(R.style.AlertDialogFullscreen);
            }
            return this;
        }

        public Builder setMaxTime(int time) {
            this.MAX_TIME = time;
            return this;
        }

        public Builder setTimeInterface(TimeInterface timeInterface) {
            this.timeInterface = timeInterface;
            return this;
        }

        /**
         * 创建一个DialogCreate对象。里面有build创建者的属性值。
         *
         * @return 返回弹窗对象
         */
        public DialogCreate build() {
            return new DialogCreate(mActivity, this);
        }
    }
}
